package simpleconfig

import (
	"errors"
	"github.com/spf13/viper"
	"os"
)

var Cfg *viper.Viper

func init() {
	Cfg = viper.New()
	Cfg.SetConfigFile("./config.yaml") // 直接配置路径
}

func LoadFromFile(file string, cfg interface{}) {
	if err := Cfg.ReadInConfig(); err != nil {
		switch err.(type) {
		case viper.ConfigFileNotFoundError:
			panic(errors.New("not config file find"))
		default:
			panic(err)
		}
	}
	err := Cfg.Unmarshal(&cfg)
	if err != nil {
		panic(err)
	}
}

func LoadFromFileByEnv(envFileName string, cfg interface{}) {
	fileName := os.Getenv(envFileName)
	if len(fileName) == 0 {
		panic("config file not find.")
	}
	LoadFromFile(fileName, cfg)
}

func LoadByDefaultFile(cfg interface{}) {
	LoadFromFile("./config.yaml", cfg)
}

func SaveToFile(fileName string) error {
	err := Cfg.SafeWriteConfigAs(fileName)
	return err
}
